package logic

import (
	"2207a/bawei/api/pkg"
	"2207a/bawei/user_srv/user"
	"context"
	"strconv"

	"2207a/bawei/api/internal/svc"
	"2207a/bawei/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginInfoMobileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginInfoMobileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginInfoMobileLogic {
	return &LoginInfoMobileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginInfoMobileLogic) LoginInfoMobile(req *types.LoginInfoMobileRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	res, err := l.svcCtx.UserSrv.GetSendSms(l.ctx, &user.GetSendSmsRequest{
		Mobile: req.Mobile,
		Source: "Login",
	})
	if err != nil {
		return &types.Response{
			Code:    -1,
			Message: "获取短信错误",
			Data:    nil,
		}, nil
	}
	if res.Code != req.Code {
		return &types.Response{
			Code:    -2,
			Message: "获取短信验证错误",
			Data:    nil,
		}, nil
	}
	userRes, err := l.svcCtx.UserSrv.LoginInfoMobile(l.ctx, &user.LoginInfoMobileRequest{
		Mobile: req.Mobile,
		Code:   req.Code,
	})
	if userRes.UserId == 0 {
		return &types.Response{
			Code:    -3,
			Message: "用户不存在",
			Data:    nil,
		}, nil
	}
	token, err := pkg.GetJwtToken(strconv.FormatInt(userRes.UserId, 10))
	if err != nil {
		return nil, err
	}
	return &types.Response{
		Code:    200,
		Message: "登录成功",
		Data: map[string]interface{}{
			"Token": token,
		},
	}, nil
}
